package du.contact2018;

import android.app.ListActivity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import du.contact2018.database.SqlMethod;
import du.contact2018.model.TreeElement;

public class SplashActivity extends ListActivity {

    TreeViewAdapter treeViewAdapter;
    private ArrayList<TreeElement> nodeList = new ArrayList<>();
    //  private TreeDataProvider treeDataProvider = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_splash);


        ListView listView = getListView();// (ListView) findViewById(R.id.main_activity_listview_contact);


        // TODO: 2018/12/31 从数据库中获取数据，填入到  List<TreeElement>


        TreeElement elementUnit;
        TreeElement elementDept;
        TreeElement elementName;


        //第一层：查询 所有的学校
        SqlMethod sqlMethod = new SqlMethod(this);
        LinkedHashMap<String, String> idUnitMap = sqlMethod.findIdUnitMap();

        // 如：没有学校
        if (idUnitMap == null) {
            return;
        }

        //添加所有的学校
        for (Map.Entry<String, String> idUnitEntry : idUnitMap.entrySet()) {
            elementUnit = new TreeElement(idUnitEntry.getKey(), idUnitEntry.getValue());
            nodeList.add(elementUnit);

            //循环各个学校，查询各个学校 的 部门
            LinkedHashMap<String, String> idDeptMap = sqlMethod.findIdDeptMap(elementUnit.getTitle());
            for (Map.Entry<String, String> idDeptEntry : idDeptMap.entrySet()) {
                elementDept = new TreeElement(idDeptEntry.getKey(), idDeptEntry.getValue());
                elementUnit.getChilds().add(elementDept);

                // 循环各个部门，查询各个部门 中 教师的姓名
                LinkedHashMap<String, String> idNameMap = sqlMethod.findIdNameMap(elementUnit.getTitle(), elementDept.getTitle());
                for (Map.Entry<String, String> idNameEntry : idNameMap.entrySet()) {
                    elementName = new TreeElement(idNameEntry.getKey(), idNameEntry.getValue());
                    elementDept.getChilds().add(elementName);
                }

            }
        }


        // nodeList 数据正确的
        treeViewAdapter = new TreeViewAdapter(this, R.layout.activity_splash, nodeList);


        listView.setAdapter(treeViewAdapter);

        registerForContextMenu(getListView());


    }


//        for(    int ii = 0; ii<nodeList.size();ii++)    {
//
//        //第二层：查询并添加  所有的学校 之 所有的部门
//        ArrayList<String> deptList = sqlMethod.findDeptArrayList(nodeList.get(ii).getTitle());
//
//        String unitID = nodeList.get(ii).getId();
//        for (int iii = 0; iii < deptList.size(); iii++) {
//
//            elementDept = new TreeElement(ii + "_" + iii, deptList.get(iii));
//            nodeList.get(ii).addChild(elementDept);
//
//            //第三层： 查询并添加  各学校、各部门 之下 所有的教师
//            ArrayList<String> nameArrayList = sqlMethod.findNameArrayList(nodeList.get(ii).getTitle(), nodeList.get(ii).getChilds().get(iii).getTitle());
//
//            // String deptID = nodeList.get(i).getChilds().get(i1).getId();
//            for (int iiii = 0; iiii < nameArrayList.size(); iiii++) {
//                elementName = new TreeElement(ii + "_" + iii + "_" + iiii, nameArrayList.get(iiii));
//                nodeList.get(ii).getChilds().get(iii).addChild(elementName);
//            }
//        }
//    }


    private class TreeViewAdapter extends ArrayAdapter {

        private LayoutInflater inflater;
        private ArrayList<TreeElement> treeElementArrayList;
        private Bitmap mIconCollapse;
        private Bitmap mIconExpand;


        public TreeViewAdapter(@NonNull Context context, int resource, @NonNull List objects) {
            super(context, resource, objects);

            inflater = LayoutInflater.from(context);
            treeElementArrayList = (ArrayList<TreeElement>) objects;
            mIconCollapse = BitmapFactory.decodeResource(context.getResources(), R.drawable.plus);
            mIconExpand = BitmapFactory.decodeResource(context.getResources(), R.drawable.cut);
        }


        @Override
        public int getCount() {
            return treeElementArrayList.size();
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Nullable
        @Override
        public TreeElement getItem(int position) {
            return treeElementArrayList.get(position);
        }

        @NonNull
        @Override
        public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
            ViewHolder holder;
            convertView = inflater.inflate(R.layout.item_contact_detail, null);
            holder = new ViewHolder();
            holder.text = (TextView) convertView.findViewById(R.id.treetext);
            holder.icon = (ImageView) convertView.findViewById(R.id.icon);
            convertView.setTag(holder);

            final TreeElement obj = treeElementArrayList.get(position);

            holder.text.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    Log.i("TreeView", "obj.id:" + obj.getId());
                    obj.forward(SplashActivity.this);
                }
            });

            int level = obj.getLevel();
            holder.icon.setPadding(25 * (level + 1), holder.icon.getPaddingTop(), 0, holder.icon.getPaddingBottom());
            holder.text.setTextColor(Color.BLUE);
            holder.text.setText(obj.getTitle());
            if (obj.isHasChild() && (obj.isExpanded() == false)) {
                holder.icon.setImageBitmap(mIconCollapse);
            } else if (obj.isHasChild() && (obj.isExpanded() == true)) {
                holder.icon.setImageBitmap(mIconExpand);
            } else if (!obj.isHasChild()) {
                holder.icon.setImageBitmap(mIconCollapse);
                holder.icon.setVisibility(View.INVISIBLE);
            }


            return convertView;
        }

        class ViewHolder {
            ImageView icon;
            TextView text;
        }

    }


    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);
        Log.i("TreeView", "position:" + position);
        if (!nodeList.get(position).isHasChild()) {
            Toast.makeText(this, nodeList.get(position).getTitle(), Toast.LENGTH_LONG);
            return;
        }

        if (nodeList.get(position).isExpanded()) {
            nodeList.get(position).setExpanded(false);
            TreeElement element = nodeList.get(position);
            ArrayList<TreeElement> temp = new ArrayList<TreeElement>();

            for (int i = position + 1; i < nodeList.size(); i++) {
                if (element.getLevel() >= nodeList.get(i).getLevel()) {
                    break;
                }
                temp.add(nodeList.get(i));
            }

            nodeList.removeAll(temp);

            treeViewAdapter.notifyDataSetChanged();

        } else {
            TreeElement obj = nodeList.get(position);
            obj.setExpanded(true);
            int level = obj.getLevel();
            int nextLevel = level + 1;

            for (TreeElement element : obj.getChilds()) {
                element.setLevel(nextLevel);
                element.setExpanded(false);
                nodeList.add(position + 1, element);

            }
            treeViewAdapter.notifyDataSetChanged();
        }
    }


}
